/*
 * This file is part of Plop Messenger.
 *
 * Plop Messenger is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 *  Plop Messenger is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Plop Messenger.  If not, see <http://www.gnu.org/licenses/>.
 */
package pm.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class Options implements Serializable {
	private static final long serialVersionUID = 1L;

	public static Options loadFrom(String file) {
		File fichier = new File(file);
		Options options;
		try {
			ObjectInputStream input = new ObjectInputStream(
					new FileInputStream(fichier));
			options = (Options) input.readObject();
			input.close();
		} catch (Exception e) {
			options = new Options();
		}
		return options;
	}

	private Map<String, Object> options = new HashMap<String, Object>();

	public boolean exists(String id) {
		return options.containsKey(id);
	}

	public boolean getBool(String id, boolean defaut) {
		return getObject(id, defaut);
	}

	public int getInt(String id, int defaut) {
		return getObject(id, defaut);
	}

	public <T> T getObject(String id) {
		return (T) options.get(id);
	}

	public <T> T getObject(String id, T defaut) {
		if (!exists(id))
			return defaut;
		return (T) options.get(id);
	}

	public String getString(String id, String defaut) {
		return getObject(id, defaut);
	}

	public void remove(String id) {
		options.remove(id);
	}

	public void saveAs(String file) throws IOException {
		File fichier = new File(file);
		if (fichier.exists())
			fichier.delete();
		fichier.createNewFile();
		ObjectOutputStream output = new ObjectOutputStream(
				new FileOutputStream(fichier));
		output.writeObject(this);
		output.close();
	}

	public void setBool(String id, boolean o) {
		setObject(id, o);
	}

	public void setInt(String id, int o) {
		setObject(id, o);
	}

	public void setObject(String id, Object o) {
		options.remove(id);
		options.put(id, o);
	}

	public void setString(String id, String o) {
		setObject(id, o);
	}
}
